/**
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import { computed, defineComponent, ref, SetupContext, watch } from 'vue';
import { CalendarNavbarProps, calendarNavbarProps } from './calendar-navbar.props';
import { ActiveMonth } from '../../types/month';

import './calendar-navbar.css';

export default defineComponent({
    name: 'FDatePickerCalendarNavbar',
    props: calendarNavbarProps,
    emits: ['clickMonth', 'clickYear', 'prePage', 'preRecord', 'nextRecord', 'nextPage'] as (string[] & ThisType<void>) | undefined,
    setup(props: CalendarNavbarProps, context: SetupContext) {
        return () => {
            const ariaLabelPrevMonth = ref(props.ariaLabelPrevMonth);
            const ariaLabelNextMonth = ref(props.ariaLabelNextMonth);
            const dateFormat = ref(props.dateFormat);
            const disablePrePageButton = ref(props.disablePrePage);
            const disablePreRecordButton = ref(props.disablePreRecord);
            const disableNextRecordButton = ref(props.disableNextRecord);
            const disableNextPageButton = ref(props.disableNextPage);
            const activeMonth = ref<ActiveMonth>(props.activeMonth as ActiveMonth);
            const years = ref(props.years);
            const selectingMonth = ref(props.selectingMonth);
            const selectingYear = ref(props.selectingYear);
            const selectMode = ref(props.selectMode);

            const yearSelector = ref(true);
            const monthSelector = ref(true);

            watch(
                () => props.activeMonth,
                () => {
                    activeMonth.value = {
                        month: props.activeMonth?.month,
                        year: props.activeMonth?.year,
                        displayTextOfMonth: props.activeMonth?.displayTextOfMonth,
                        displayTextOfYear: props.activeMonth?.displayTextOfMonth
                    };
                }
            );

            const navbarClass = computed(() => {
                const classObject = {
                    'f-datepicker-header': true,
                    monthYearSelBarBorder: selectingMonth.value || selectingYear.value
                } as Record<string, boolean>;
                return classObject;
            });

            const prePageButtonClass = computed(() => {
                const classObject = {
                    'f-datepicker-header-btn': true,
                    'f-datepicker-header-btn-disabled': disablePrePageButton.value
                } as Record<string, boolean>;
                return classObject;
            });

            const shouldShowNavRecordButton = computed(() => {
                return !selectingMonth.value && !selectingYear.value;
            });

            const preRecordButtonClass = computed(() => {
                const classObject = {
                    'f-datepicker-header-btn': true,
                    'f-datepicker-header-btn-disabled': disablePreRecordButton.value
                } as Record<string, boolean>;
                return classObject;
            });

            const nextRecordButtonClass = computed(() => {
                const classObject = {
                    'f-datepicker-header-btn': true,
                    'f-datepicker-header-btn-disabled': disableNextRecordButton.value
                } as Record<string, boolean>;
                return classObject;
            });

            const nextPageButtonClass = computed(() => {
                const classObject = {
                    'f-datepicker-header-btn': true,
                    'f-datepicker-header-btn-disabled': disableNextPageButton.value
                } as Record<string, boolean>;
                return classObject;
            });

            const navbarSelectYearButtonClass = computed(() => {
                const classObject = {
                    'f-datepicker-header-btn': true,
                    'f-datepicker-yearLabel': yearSelector.value,
                    'f-datepicker-labelBtnNotEdit': !yearSelector.value
                } as Record<string, boolean>;
                return classObject;
            });

            const navbarSelectMonthButtonClass = computed(() => {
                const classObject = {
                    'f-datepicker-header-btn': true,
                    'f-datepicker-monthLabel': monthSelector.value,
                    'f-datepicker-labelBtnNotEdit': !monthSelector.value
                } as Record<string, boolean>;
                return classObject;
            });

            const formateType = computed(() => {
                const yIndex = dateFormat.value ? dateFormat.value.indexOf('yyyy') : 0;
                const mIndex = dateFormat.value ? dateFormat.value.indexOf('MM') : 0;
                return yIndex > mIndex ? `${'MM'}-${'yyyy'}` : `${'yyyy'}-${'MM'}`;
            });

            function navigateToPreviousPage($event: MouseEvent) {
                $event.stopPropagation();
                context.emit('prePage');
            }

            function navigateToPreviousRecord($event: MouseEvent) {
                $event.stopPropagation();
                context.emit('preRecord');
            }

            function onClearActiveYear($event: MouseEvent) {
                $event.stopPropagation();
                context.emit('clickYear');
            }

            function onClickActiveMonth($event: MouseEvent) {
                $event.stopPropagation();
                context.emit('clickMonth');
            }

            function navigateToNextRecord($event: MouseEvent) {
                $event.stopPropagation();
                $event.stopPropagation();
                context.emit('nextRecord');
            }

            function navigateToNextPage($event: MouseEvent) {
                $event.stopPropagation();
                context.emit('nextPage');
            }

            function renderSelectYearButton() {
                return (
                    <button
                        type="button"
                        class={navbarSelectYearButtonClass.value}
                        onClick={(payload: MouseEvent) => {
                            yearSelector.value && onClearActiveYear(payload);
                        }}
                        tabindex={yearSelector.value ? '0' : '-1'}
                        disabled={selectMode.value === 'year'}>
                        {!selectingYear.value
                            ? activeMonth.value.displayTextOfYear
                            : years.value.length > 3
                            ? (years.value[0][1] as any).year + ' - ' + (years.value[3][1] as any).year
                            : ''}
                    </button>
                );
            }

            function renderSelectMonthButton() {
                return (
                    !selectingYear.value &&
                    selectMode.value !== 'month' && (
                        <button
                            type="button"
                            class={navbarSelectMonthButtonClass.value}
                            onClick={(payload: MouseEvent) => {
                                monthSelector.value && onClickActiveMonth(payload);
                            }}
                            tabindex={monthSelector.value ? '0' : '-1'}>
                            {activeMonth.value.displayTextOfMonth}
                        </button>
                    )
                );
            }

            return (
                <div class={navbarClass.value}>
                    <div class="f-datepicker-prev-btn">
                        <button title="prePage" type="button" class={prePageButtonClass.value} onClick={navigateToPreviousPage}>
                            <i class="k-icon k-i-arrow-double-60-left"></i>
                        </button>
                        {shouldShowNavRecordButton.value && (
                            <button
                                type="button"
                                aria-label={ariaLabelPrevMonth.value}
                                class={preRecordButtonClass.value}
                                onClick={navigateToPreviousRecord}>
                                <i class="k-icon k-i-arrow-chevron-left"></i>
                            </button>
                        )}
                    </div>
                    <div class="f-datepicker-monthYearText">
                        {formateType.value === 'yyyy-MM'
                            ? [renderSelectYearButton(), renderSelectMonthButton()]
                            : [renderSelectMonthButton(), renderSelectYearButton()]}
                    </div>
                    <div class="f-datepicker-next-btn">
                        {shouldShowNavRecordButton.value && (
                            <button
                                type="button"
                                aria-label={ariaLabelNextMonth.value}
                                class={nextRecordButtonClass.value}
                                onClick={navigateToNextRecord}>
                                <i class="k-icon k-i-arrow-chevron-right"></i>
                            </button>
                        )}
                        <button title="nextPage" type="button" class={nextPageButtonClass.value} onClick={navigateToNextPage}>
                            <i class="k-icon k-i-arrow-double-60-right"></i>
                        </button>
                    </div>
                </div>
            );
        };
    }
});
